package config_service

import (
	"gorm.io/gorm"
	cd "pear-admin-layui-go/app/sys/config/domain"
	fd "pear-admin-layui-go/framework/database"
)

func EditPage(id int64) *cd.Config {
	var c = cd.Config{
		Id: id,
	}
	fd.Db.Select("id", "name", "value", "remark").First(&c)
	return &c
}

func Enable(cer *cd.ConfigEnableRequest) *gorm.DB {
	return fd.Db.Model(cd.Config{Id: cer.Id}).Select("enable", "update_time", "update_name",
		"update_by").Updates(cd.Config{Enable: cer.Enable, UpdateTime: cer.UpdateTime, UpdateName: cer.UpdateName,
		UpdateBy: cer.UpdateBy})
}

func Edit(cer *cd.ConfigEditRequest) *gorm.DB {
	r := fd.Db.Model(cd.Config{Id: cer.Id}).Select("name", "value", "remark", "update_time", "update_name",
		"update_by").Updates(cd.Config{Name: cer.Name, Value: cer.Value, Remark: cer.Remark,
		UpdateTime: cer.UpdateTime, UpdateName: cer.UpdateName, UpdateBy: cer.UpdateBy})
	return r
}

func Save(csr *cd.ConfigSaveRequest) (cd.Config, error) {
	c := cd.Config{
		Name:       csr.Name,
		Value:      csr.Value,
		Enable:     csr.Enable,
		Remark:     csr.Remark,
		CreateTime: csr.CreateTime,
		CreateName: csr.CreateName,
		CreateBy:   csr.CreateBy,
	}
	result := fd.Db.Create(&c)
	return c, result.Error
}

func Table(csr *cd.ConfigSearchRequest) ([]cd.Config, int64) {
	var count int64
	db := fd.Db.Model(cd.Config{})
	db.Where("del_flag = false")
	if csr.Name != "" {
		db.Where("name like ?", "%"+csr.Name+"%")
	}
	db.Count(&count)
	var configs []cd.Config
	db.Limit(csr.Limit).Offset((csr.Page-1)*csr.Limit).Select("id", "name", "value", "enable", "remark",
		"create_time", "create_name", "update_time", "update_name").Find(&configs)
	return configs, count
}
